import { isString } from '@/utils/type';
const crypto = require('crypto-js');
const { default: JSEncrypt } = require('jsencrypt');

const AES_ENCRYPT_KEY = 'abcdefgabcdefg12';
// AES加密（CBC模式，需要偏移量）
const AES_ENCRYPT_CBCIV = 'yqldxfsmbd531996';

/**
 * AES对称加密
 * @param {*} data
 * @returns
 */
export function aesEncrypt(data) {
  const key = crypto.enc.Utf8.parse(AES_ENCRYPT_KEY);
  if (!isString(data)) {
    data = JSON.stringify(data);
  }
  const secretData = crypto.enc.Utf8.parse(data);

  return {
    key,
    text: crypto.AES.encrypt(secretData, key, {
      mode: crypto.mode.CBC,
      padding: crypto.pad.Pkcs7,
      iv: crypto.enc.Utf8.parse(AES_ENCRYPT_CBCIV),
    }).toString(),
  };
}

/**
 * AES解密
 * @param {*} encryptData
 * @returns
 */
export function aesDecrypt(encryptData) {
  if (!isString(encryptData)) {
    throw new Error('解密数据应为String类型');
  }

  const key = crypto.enc.Utf8.parse(AES_ENCRYPT_KEY);
  const decrypt = crypto.AES.decrypt(encryptData, key, {
    mode: crypto.mode.CBC,
    padding: crypto.pad.Pkcs7,
    iv: crypto.enc.Utf8.parse(AES_ENCRYPT_CBCIV),
  });

  return crypto.enc.Utf8.stringify(decrypt).toString();
}

export function initRsaEncryptor(key) {
  // RSA公钥
  // const RSA_PUBLIC_KEY =
  //   'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCyFNEYykLDfd0f2PoX46/j9Jk+AmnTLFh8Yd2YaEIShLWBNnuvoGgxEIAhoKNHlWF43glhNUzFW/UG39E6cp0iTT5O7NJeDi3tPL58x6fdAi7OivKwZKuug41v88WNlIi2xwcEdx/M4kpa7nr7Wa3uaTInZzOGBuLlot0OCXdVdwIDAQAB';
  const encryptor = new JSEncrypt();
  // 设置公钥
  encryptor.setPublicKey(key);
  return encryptor;
}

/**
 * RSA加密 针对用户名、密码等敏感信息
 * @param {*} data
 * @returns
 */
export function rsaEncrypt(data, key) {
  const encryptor = initRsaEncryptor(key);
  return encryptor.encrypt(data);
}
